package server.model.dbms;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import model.dto.SQLConnectionDTO;
import server.model.properties.PropertiesLoader;


public class SQLInstanceManager {
	private static Connection instance=createConnection();

	private SQLInstanceManager(){}

	public Object clone() throws CloneNotSupportedException{
		throw new CloneNotSupportedException("Singleton Pattern");
	}

	public static synchronized Connection getConnection(){
		if(instance==null)
			createConnection();
		return instance;
	}

	private static Connection createConnection(){
		SQLConnectionDTO dto=null;
		try {
			dto=PropertiesLoader.loadDBMSProperties(System.getProperty("user.dir") + "/data/dbmsconfig.prp");
			Class.forName(dto.getDriver()).newInstance();
			return DriverManager.getConnection(dto.getUrl(), dto.getUser(), dto.getPassword());
		} catch (FileNotFoundException e1) {
			e1.printStackTrace(System.err);
		} catch (IOException e1) {
			e1.printStackTrace(System.err);
		} catch (InstantiationException e) {
			e.printStackTrace(System.err);
		} catch (IllegalAccessException e) {
			e.printStackTrace(System.err);
		} catch (ClassNotFoundException e) {
			e.printStackTrace(System.err);
		} catch (SQLException e) {
			e.printStackTrace(System.err);
		}
		return null;
    }
}
